<template>
  <div class="topRatedMovies">
    <p>{{ title }}</p>
    <van-swipe class="movies" :loop="false" :show-indicators="false" width="100">
      <van-swipe-item v-for="movie in movieList" :key="movie.movieId">
        <img class="thumb" :src="movie.poster" :alt="movie.name" @click="gotoMovieDetail(movie.movieId)" />
        <h5>{{ movie.name }}</h5>
      </van-swipe-item>
    </van-swipe>
  </div>
</template>

<script setup>
import { fetchTopRatedMovies } from '@/api/index.js'
import { onMounted, computed } from 'vue'
import { useStore } from '@/stores/index.js'
const store = useStore()
import { useRouter } from 'vue-router'

const router = useRouter()

// const title = ref('')
// const movieList = ref([])

const title = computed(() => store.topRankTitle)
const movieList = computed(() => store.topRankMovies)

onMounted(async () => {
  // console.log('TopRateMoviesCmp mounted')

  // 判断store中是否有topRankTitle和topRankMovies，如果没有则从api获取数据
  if (!store.topRankTitle) {
    const res = await fetchTopRatedMovies()
    store.setTopRankTitle(res.title)
    store.setTopRankMovies(res.movieList)
  }
});

const gotoMovieDetail = (movieId) => {
  router.push({ path: `/movie/${movieId}` })
};



</script>

<style scoped>
.topRatedMovies {
  /* padding: 10px; */
  background-color: #fff;
  margin-top: 50.5px;
}

.topRatedMovies p {
  font-size: 14px;
  color: #333;
  padding: 15px 10px;
  margin: 0;
}

.movies {
  padding: 0 5px;
  width: 100%;
  box-sizing: border-box;
}

.movies h5 {
  width: 90px;
}

:deep(.van-swipe__track) {
  /* width: 100% !important; */
  flex-wrap: nowrap;
  box-sizing: border-box;
}

:deep(.van-swipe-item) {
  width: 100px;
  height: auto;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  /* margin-right: 10px; */
}

img.thumb {
  cursor: pointer;
  display: block;
  width: 90px;
  height: 125px;
  object-fit: cover;
  position: relative;
  margin-bottom: 10px;
}

h5 {
  width: 100%;
  color: #333;
  text-align: center;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  margin-top: 0;
}
</style>
